<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { queryByUserIdApi } from '@/api/maintenance';
import { queryByUserIdApi as queryRepairByUserIdApi } from '@/api/repair';

const router = useRouter();

// 选项卡激活状态
const activeTab = ref('maintenance');

// 用户信息相关
const loginUser = ref(null);

// 保养记录数据
const maintenanceRecords = ref([]);
const maintenanceLoading = ref(false);
const filteredMaintenanceRecords = ref([]);

// 维修记录数据
const repairRecords = ref([]);
const repairLoading = ref(false);
const filteredRepairRecords = ref([]);

// 根据状态获取标签类型 

const getTagType = (status) => { 

const typeMap = { 

'待确认': 'warning', 

'已确认': 'primary', 

'工作中': 'info', 

'已完成': 'success', 

'已取消': 'danger' 

}; 

return typeMap[status] || 'info'; 

}; 

// 格式化状态显示 

const formatStatus = (status) => { 

const statusMap = { 

'待确认': '待确认', 

'已确认': '已确认', 

'工作中': '工作中', 

'已完成': '已完成', 

'已取消': '已取消' 

}; 

return statusMap[status] || status; 

};

// 获取保养记录
const getMaintenanceRecords = async () => {
  const loginUserStr = localStorage.getItem('loginUser');
  if (!loginUserStr) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }
  
  const loginUser = JSON.parse(loginUserStr);
  maintenanceLoading.value = true;
  
  try {
      // 使用正确的API函数根据用户ID查询保养预约
      const result = await queryByUserIdApi(loginUser.id);
      
      if (result.code) {
      // 处理API返回的数据
      maintenanceRecords.value = Array.isArray(result.data) ? result.data : (result.data?.records || result.data?.list || []);
      filteredMaintenanceRecords.value = maintenanceRecords.value;
    } else {
      ElMessage.error(result.msg || '获取保养记录失败');
      maintenanceRecords.value = [];
      filteredMaintenanceRecords.value = [];
    }
  } catch (error) {
    ElMessage.error('获取保养记录失败，请稍后重试');
    maintenanceRecords.value = [];
    filteredMaintenanceRecords.value = [];
  } finally {
    maintenanceLoading.value = false;
  }
};

// 获取维修记录
const getRepairRecords = async () => {
  const loginUserStr = localStorage.getItem('loginUser');
  if (!loginUserStr) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }
  
  const loginUser = JSON.parse(loginUserStr);

  repairLoading.value = true;
  
  try {
    // 使用导入的API函数，与保养记录API调用保持一致
    const result = await queryRepairByUserIdApi(loginUser.id);

    
    if (result.code) {
      // 处理API返回的数据
      repairRecords.value = Array.isArray(result.data) ? result.data : (result.data?.records || result.data?.list || []);
      filteredRepairRecords.value = repairRecords.value;
      
      // 如果确实没有数据，显示提示信息
    } else {
      ElMessage.error(result.msg || '获取维修记录失败');
      repairRecords.value = [];
      filteredRepairRecords.value = [];
    }
  } catch (error) {
    if (error.stack) {
    }
    ElMessage.error('获取维修记录失败，请稍后重试');
    repairRecords.value = [];
    filteredRepairRecords.value = [];
  } finally {
    repairLoading.value = false;

  }
};

// 切换选项卡
const handleTabChange = (tabName) => {
  activeTab.value = tabName;
  if (tabName === 'repair') {
    // 无论是否已有数据，都重新获取，确保数据最新
    getRepairRecords();
  }
};

// 移除分页相关函数



// 页面加载时获取记录
onMounted(() => {
  const loginUserStr = localStorage.getItem('loginUser');
  if (loginUserStr) {
    loginUser.value = JSON.parse(loginUserStr);
    console.log('用户已登录，ID:', loginUser.value.id);
    // 页面加载时同时获取保养和维修记录
    getMaintenanceRecords();
    setTimeout(() => {
      getRepairRecords();
    }, 1000); // 延迟1秒调用，确保保养记录查询完成后再查询维修记录
  } else {
    ElMessage.warning('请先登录');
    router.push('/login');
  }
});
</script>

<template>
  <div class="records-container">
    <h1>我的服务记录</h1>
    <br>
    
    <!-- 选项卡切换 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="保养记录" name="maintenance">
        <div class="records-content">
          <el-table 
            v-loading="maintenanceLoading" 
            :data="filteredMaintenanceRecords" 
            border 
            style="width: 100%"
            empty-text="暂无保养记录"
          >
            <el-table-column prop="id" label="预约编号" width="100" align="center"></el-table-column>
            <el-table-column label="预约日期" width="120" align="center">
              <template #default="scope">
                {{ scope.row.appointment_date || scope.row.appointmentDate || '' }}
              </template>
            </el-table-column>
            <el-table-column label="预约时间" width="100" align="center">
              <template #default="scope">
                {{ scope.row.appointment_time || scope.row.appointmentTime || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="保养说明" show-overflow-tooltip></el-table-column>
            <el-table-column label="联系电话" width="120" align="center">
                <template #default="scope">
                  {{ scope.row.contact_phone || scope.row.contactPhone || '' }}
                </template>
              </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getTagType(scope.row.status || '待确认')">{{ formatStatus(scope.row.status || '待确认') }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="empName" label="保养员" width="100" align="center"></el-table-column>
            <el-table-column label="创建时间" width="180" align="center">
              <template #default="scope">
                {{ scope.row.created_at || scope.row.createdAt || scope.row.create_at || scope.row.createTime || '' }}
              </template>
            </el-table-column>

          </el-table>
          
          <!-- 移除分页组件 -->
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="维修记录" name="repair">
        <div class="records-content">
          <el-table 
            v-loading="repairLoading" 
            :data="filteredRepairRecords" 
            border 
            style="width: 100%"
            empty-text="暂无维修记录"
          >
            <el-table-column prop="id" label="预约编号" width="100" align="center"></el-table-column>
            <el-table-column label="预约日期" width="120" align="center">
              <template #default="scope">
                {{ scope.row.appointment_date || scope.row.appointmentDate || '' }}
              </template>
            </el-table-column>
            <el-table-column label="预约时间" width="100" align="center">
              <template #default="scope">
                {{ scope.row.appointment_time || scope.row.appointmentTime || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="故障说明" show-overflow-tooltip></el-table-column>
            <el-table-column label="联系电话" width="120" align="center">
                <template #default="scope">
                  {{ scope.row.contact_phone || scope.row.contactPhone || '' }}
                </template>
              </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getTagType(scope.row.status || '待确认')">{{ formatStatus(scope.row.status || '待确认') }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="empName" label="维修员" width="100" align="center"></el-table-column>
            <el-table-column label="创建时间" width="180" align="center">
              <template #default="scope">
                {{ scope.row.created_at || scope.row.createdAt || scope.row.create_at || scope.row.createTime || '' }}
              </template>
            </el-table-column>

          </el-table>
          
          <!-- 移除分页组件 -->
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.records-container {
  padding: 20px;
  background-color: #fff;
}

.records-content {
  margin-top: 20px;
  min-height: 400px;
}

.records-content :deep(.el-table__row) {
  height: 48px;
}

.records-content :deep(.el-table__row > td) {
  padding: 12px 0;
}
</style>